// OKX Wallet connection utilities for Solana only
export type WalletAccount = {
  solanaAddress: string
  solanaBalance?: string
}

export type WalletConnectionState = {
  connected: boolean
  account: WalletAccount | null
  error: string | null
}

// Check if OKX Wallet is installed
export const isOKXWalletInstalled = (): boolean => {
  // @ts-ignore - okxwallet is injected by the browser extension
  return typeof window !== "undefined" && !!window.okxwallet
}

// Connect to OKX Wallet - Solana only
export const connectOKXWallet = async (): Promise<WalletConnectionState> => {
  try {
    if (!isOKXWalletInstalled()) {
      return {
        connected: false,
        account: null,
        error: "OKX Wallet extension not installed",
      }
    }

    // @ts-ignore - okxwallet is injected by the browser extension
    const provider = window.okxwallet

    try {
      // Try different methods to connect to Solana in OKX Wallet
      let solanaAddress = null

      // Method 1: Try using the standard Phantom-compatible method
      try {
        // Check if the solana property exists
        if (provider.solana) {
          const response = await provider.solana.connect()
          solanaAddress = response.publicKey.toString()
        }
      } catch (err) {
        console.log("Method 1 failed:", err)
      }

      // Method 2: Try using wallet_requestAccounts with solana chainId
      if (!solanaAddress) {
        try {
          const accounts = await provider.request({
            method: "wallet_requestAccounts",
            params: [{ chainId: "solana" }],
          })
          if (accounts && accounts.length > 0) {
            solanaAddress = accounts[0]
          }
        } catch (err) {
          console.log("Method 2 failed:", err)
        }
      }

      // Method 3: Try using wallet_switchNetwork to Solana first
      if (!solanaAddress) {
        try {
          await provider.request({
            method: "wallet_switchNetwork",
            params: ["solana"],
          })

          // Then try to get accounts
          const accounts = await provider.request({
            method: "eth_requestAccounts",
          })

          if (accounts && accounts.length > 0) {
            solanaAddress = accounts[0]
          }
        } catch (err) {
          console.log("Method 3 failed:", err)
        }
      }

      // Method 4: Try using a direct connect method
      if (!solanaAddress) {
        try {
          const result = await provider.request({
            method: "connect",
          })

          if (result && result.publicKey) {
            solanaAddress = result.publicKey.toString()
          }
        } catch (err) {
          console.log("Method 4 failed:", err)
        }
      }

      // If we got a Solana address through any method
      if (solanaAddress) {
        // Get Solana balance (optional)
        let solanaBalance = null
        try {
          // Try different methods to get balance
          try {
            const balanceResult = await provider.request({
              method: "getBalance",
              params: [solanaAddress],
            })

            if (balanceResult && balanceResult.value) {
              // Convert lamports to SOL (1 SOL = 1,000,000,000 lamports)
              solanaBalance = (balanceResult.value / 1000000000).toFixed(4)
            }
          } catch (err) {
            console.log("Balance method 1 failed:", err)

            // Try alternative balance method
            try {
              if (provider.solana) {
                const balance = await provider.solana.getBalance()
                solanaBalance = (balance / 1000000000).toFixed(4)
              }
            } catch (err2) {
              console.log("Balance method 2 failed:", err2)
            }
          }
        } catch (balanceError) {
          console.warn("Failed to get Solana balance:", balanceError)
        }

        return {
          connected: true,
          account: {
            solanaAddress: solanaAddress,
            solanaBalance: solanaBalance,
          },
          error: null,
        }
      } else {
        return {
          connected: false,
          account: null,
          error: "Could not connect to Solana. Please make sure you have a Solana wallet configured in OKX Wallet.",
        }
      }
    } catch (error: any) {
      console.error("Error connecting to Solana:", error)
      return {
        connected: false,
        account: null,
        error: error.message || "Failed to connect to Solana",
      }
    }
  } catch (error: any) {
    console.error("Error connecting to OKX Wallet:", error)
    return {
      connected: false,
      account: null,
      error: error.message || "Failed to connect to OKX Wallet",
    }
  }
}

// Disconnect from OKX Wallet
export const disconnectWallet = (): WalletConnectionState => {
  return {
    connected: false,
    account: null,
    error: null,
  }
}

// Listen for account changes
export const setupAccountChangeListener = (callback: (accounts: string[]) => void): void => {
  if (isOKXWalletInstalled()) {
    try {
      // @ts-ignore - okxwallet is injected by the browser extension
      if (window.okxwallet.solana) {
        // @ts-ignore
        window.okxwallet.solana.on("accountChanged", (publicKey) => {
          if (publicKey) {
            callback([publicKey.toString()])
          } else {
            callback([])
          }
        })
      } else {
        // @ts-ignore
        window.okxwallet.on("accountsChanged", callback)
      }
    } catch (err) {
      console.error("Error setting up account change listener:", err)
    }
  }
}

// Format address for display
export const formatAddress = (address: string | undefined): string => {
  if (!address) return ""
  return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`
}
